package com.emmmya.ocs.modules.system.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.emmmya.ocs.modules.system.file.entity.File;
import com.emmmya.ocs.common.utils.CheckStrength;
import com.emmmya.ocs.common.utils.CommonUtil;
import com.emmmya.ocs.common.utils.ResultUtil;
import com.emmmya.ocs.common.utils.ShiroUtil;
import com.emmmya.ocs.common.vo.Result;
import com.emmmya.ocs.modules.system.entity.Role;
import com.emmmya.ocs.modules.system.entity.User;
import com.emmmya.ocs.modules.system.file.service.FileService;
import com.emmmya.ocs.modules.system.service.RoleService;
import com.emmmya.ocs.modules.system.service.UserService;
import com.emmmya.ocs.modules.system.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @description:
 * @author: 咕噜肉IT小店-黑医
 * @createDate: 2020-05-12
 * @version: 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    ShiroUtil shiroUtils;
    @Autowired
    RoleService roleService;

    @Autowired
    FileService fileService;


    /**
     * 单文件
     */
    @RequestMapping("uploadFIle")
    @ResponseBody
    public Result<Object> onlyOneUpload(MultipartFile file) throws IOException {
        String fKey = CommonUtil.renamePic(file.getOriginalFilename());
        File save = fileService.storeFile(file, fKey, null);
        return ResultUtil.data(save,"保存成功",0);
    }

    /**
     * 校验用户名
     * @param username
     * @return
     */
    @PostMapping("checkUsername")
    @ResponseBody
    public Result<Object> checkUsername(String username){
        User user = userService.findByUsername(username);
        //List<Accounts> accountsByName = userService.findAccountsByName(username);
        if (user != null) {
            return ResultUtil.error(210,"用户名已存在,请换一个吧");
        }else{
//            if(accountsByName.isEmpty()){
//                return ResultUtils.error(210,"枫云岛玩家账号中不存在该账号，如果注册会绑定不上玩家信息。");
//            }
            return ResultUtil.success("用户名可以使用！");
        }
    }

    /**
     *  user对象里面有不同的对象嵌套 传参时候，必须使用@RequestBody,不然启动会报错，虽然不影响
     * @param vo
     * @return
     */
    @GetMapping("getUserList")
    @ResponseBody
    public Result<Object> getUserList(UserVo vo){
        //IPage<User> page = new Page<>(vo.getPage(),vo.getLimit());
        //QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        IPage<User> page = vo.createPage();
        userService.getListByPage(page,vo.createWrapper());
        return ResultUtil.data(page,"成功");
    }


    @PostMapping("register")
    @ResponseBody
    public Result<Object> add(HttpServletRequest request, HttpServletResponse response, @RequestBody User user){
        User u = userService.findByUsername(user.getUsername());
        if(u != null ){
         return   ResultUtil.error(210,"用户名已存在,请换一个吧");
        }
        try {
            //检测密码强度，导入
            String password = user.getPassword();
            int stroge = CheckStrength.checkPasswordStrengthH(password);
            if(stroge<3){
                throw new IllegalArgumentException("强度不足：至少有大写字母、小写字母、数字、特殊字符中三样。");
            }
            //
            user.setPassword(shiroUtils.encryptionToHex(password));
            //user.setRegisterIp(IpUtils.getIpAddr(request));
            //查询默认角色
            List<Role> defaultRoles = roleService.findRolesByDefaultRole(true);
            //将默认角色赋值用户上
            user.setRoles(defaultRoles);
            u = userService.save(user);
        }
        catch (IllegalArgumentException e){
            e.printStackTrace();
            return  ResultUtil.error(210,e.getMessage());
        }
//        catch (ConstraintViolationException e) {
//            e.printStackTrace();
//            Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
//            String message = "";
//            for (ConstraintViolation<?> constraintViolation : constraintViolations) {
//                message += constraintViolation.getMessage()+";";
//            }
//            return ResultUtils.error(210,message);
//        }
        catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(210,e.getMessage());
        }
        return  ResultUtil.data(u,"新增成功！");
    }

    @PostMapping("resetPassword")
    @ResponseBody
    public Result<Object> resetPassword(@RequestParam(value="userId",required = false)Long userId,
                                        @RequestParam(value="password",required = false)String password){
        if(userId == null || userId == 0 || StringUtils.isEmpty(password)){
            return ResultUtil.error("参数有误，请重试！");
        }
        try {
            User user = userService.get(userId);
            if( user == null){
                return ResultUtil.error("未查询到该用户信息，请刷新当前页面是否存在当前用户。");
            }
            int stroge = CheckStrength.checkPasswordStrengthH(password);
            if(stroge<3){
                throw new IllegalArgumentException("强度不足：至少有大写字母、小写字母、数字、特殊字符中三样。");
            }
            user.setPassword(shiroUtils.encryptionToHex(password));
            Integer result = userService.updateUser(user);
            if(result>0){
                return ResultUtil.success("修改成功！");
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return ResultUtil.error(e.getMessage());
        }
        return ResultUtil.error("未知错误，请联系系统管理员处理！");
    }


    @DeleteMapping("deleteUserById")
    @ResponseBody
    public Result<Object> add(@RequestParam("userId") Long userId){
        try {
            userService.delete(userId);
            return ResultUtil.success("删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.success("删除失败！失败消息:"+e.getMessage());
        }
    }


    @PostMapping("update")
    @ResponseBody
    public Result<Object> update(@RequestBody User user){
        Integer i = 0;
        try {
            //检测密码强度，导入
            String password = user.getPassword();
            if(!StringUtils.isEmpty(password)) {
                int stroge = CheckStrength.checkPasswordStrengthH(password);
                if (stroge < 3) {
                    throw new IllegalArgumentException("强度不足：至少有大写字母、小写字母、数字、特殊字符中三样。");
                }
                user.setPassword(shiroUtils.encryptionToHex(password));
            }
            //使用mybaits 更新。 因为jpa更新会把没有更细你的数据修改成空值
            if(user.getId() == null || user.getId() == 0){
                User byUsername = userService.findByUsername(user.getUsername());
                user.setId(byUsername.getId());
            }
            i = userService.updateUser(user);
        }
        catch (IllegalArgumentException e){
            e.printStackTrace();
            return   ResultUtil.error(210,e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        if (i != null && i > 0){
            return ResultUtil.success("保存成功！");
        }
        return ResultUtil.error(210,"保存失败！请联系管理员处理问题！");
    }

    @PostMapping("disableUser")
    @ResponseBody
    public Result<Object> disableUser(@RequestParam(value = "id",required = false)Long id){
        userService.disableUser(id);
        return null;
    }

    @PostMapping("updateUserRoles")
    @ResponseBody
    public Result<Object> updateUserRoles(@RequestParam("userId") Long userId,@RequestParam("roleIds[]") Long[] roleIds){
        try {
            User user = userService.get(userId);
            List<Role> roles = user.getRoles();
            roles.clear();
            if(user!=null){
                for (Long roleId : roleIds) {
                    Role role = roleService.get(roleId);
                    roles.add(role);
                }
                userService.update(user);
                return ResultUtil.success("更新成功！");
            }else{
                return ResultUtil.success("更新失败！用户不存在。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.success("更新失败！系统错误。错误信息:"+e.getMessage());
        }

    }



    @GetMapping("getUser")
    @ResponseBody
    public Result<Object> getUser(@RequestParam("username") String username){
        User user = userService.findByUsername(username);
        return ResultUtil.data(user);
    }

    @GetMapping("requestSession")
    @ResponseBody
    public String requestSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        int maxInactiveInterval = session.getMaxInactiveInterval();
        String requestedSessionId = request.getRequestedSessionId();
        String centent = "sessionId:"+requestedSessionId+
                "\r\nsession过期时长:"+maxInactiveInterval+"毫秒";
        return centent;

    }
}
